//
//  ImagePicker.m
//  BDKit
//
//  Created by Liu Jinyong on 16/1/20.
//  Copyright © 2016年 Baidu. All rights reserved.
//

#import <UIKit/UIKit.h>
#import "BDImagePicker.h"
#import "ClipViewController.h"
#import "UIViewController+TYSnapshot.h"
@interface BDImagePicker()<UIActionSheetDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate,ClipPhotoDelegate>

@property (nonatomic, weak) UIViewController *viewController;
@property (nonatomic, copy) BDImagePickerFinishAction finishAction;
@property (nonatomic, assign) BOOL allowsEditing;
@property (nonatomic, assign) BOOL allowsCustomEditing;
@property (nonatomic, strong)UIImagePickerController *imagePicker;
@end


static BDImagePicker *bdImagePickerInstance = nil;

@implementation BDImagePicker

+ (void)showImagePickerFromViewController:(UIViewController *)viewController allowsEditing:(BOOL)allowsEditing finishAction:(BDImagePickerFinishAction)finishAction {
    if (bdImagePickerInstance == nil) {
        bdImagePickerInstance = [[BDImagePicker alloc] init];
    }
    
    [bdImagePickerInstance showImagePickerFromViewController:viewController
                                               allowsEditing:allowsEditing
                                                finishAction:finishAction];
}

- (void)showImagePickerFromViewController:(UIViewController *)viewController
                            allowsEditing:(BOOL)allowsEditing
                             finishAction:(BDImagePickerFinishAction)finishAction {
    _viewController = viewController;
    _finishAction = finishAction;
    _allowsEditing = allowsEditing;
    

    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        WEAKSELF
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"" message:@"请选择操作类型" preferredStyle:UIAlertControllerStyleActionSheet];
            UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                STRONGSELFFor(weakSelf)
               dispatch_async(dispatch_get_main_queue(), ^{
                            UIImagePickerController *picker = [[UIImagePickerController alloc] init];
                              picker.delegate = self;
                              picker.sourceType = UIImagePickerControllerSourceTypeCamera;
                              picker.allowsEditing = strongSelf.allowsEditing;
                              picker.modalPresentationStyle = 0;
                              [strongSelf.viewController presentViewController:picker animated:YES completion:nil];
                              strongSelf.imagePicker = picker;
                                });
            }];
        UIAlertAction *okActio2n = [UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            STRONGSELFFor(weakSelf)
            dispatch_async(dispatch_get_main_queue(), ^{
                    
                                  UIImagePickerController *picker = [[UIImagePickerController alloc] init];
                                      picker.delegate = self;
                                      picker.allowsEditing = strongSelf.allowsEditing;
                                      picker.modalPresentationStyle = 0;
                                      [ strongSelf.viewController presentViewController:picker animated:YES completion:nil];
                                      strongSelf.imagePicker = picker;
                                });
                    
           
        }];
            //初始化一个UIAlertController的警告框将要用到的UIAlertAction style cancle
            UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                
            }];
            //将初始化好的UIAlertAction添加到UIAlertController中
            [alertController addAction:okAction];
            [alertController addAction:okActio2n];
            [alertController addAction:cancleAction];
           dispatch_async(dispatch_get_main_queue(), ^{
           [self.viewController presentViewController:alertController animated:true completion:nil];
                 
                                     });
         
           
           
       }else {
           WEAKSELF
           UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"" message:@"请选择操作类型" preferredStyle:UIAlertControllerStyleActionSheet];

            UIAlertAction *okActio2n = [UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                STRONGSELFFor(weakSelf)
                dispatch_async(dispatch_get_main_queue(), ^{
                        
                                      UIImagePickerController *picker = [[UIImagePickerController alloc] init];
                                          picker.delegate = self;
                                          picker.allowsEditing = strongSelf.allowsEditing;
                                          picker.modalPresentationStyle = 0;
                                          [ strongSelf.viewController presentViewController:picker animated:YES completion:nil];
                                          strongSelf.imagePicker = picker;
                                    });
                        
               
            }];
              
                UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                    
                }];
    
                [alertController addAction:okActio2n];
                [alertController addAction:cancleAction];
               
                  dispatch_async(dispatch_get_main_queue(), ^{
                      [self.viewController presentViewController:alertController animated:true completion:nil];
                            
                                                });
           
       }

}

+ (void)showImagePickerFromViewController:(UIViewController *)viewController
                      allowsCustomEditing:(BOOL)allowsEditing
                             finishAction:(BDImagePickerFinishAction)finishAction{
    if (bdImagePickerInstance == nil) {
        bdImagePickerInstance = [[BDImagePicker alloc] init];
    }
    
    [bdImagePickerInstance showImagePickerFromViewController:viewController
                                               allowsCustomEditing:allowsEditing
                                                finishAction:finishAction];
    
}
- (void)showImagePickerFromViewController:(UIViewController *)viewController
                            allowsCustomEditing:(BOOL)allowsEditing
                             finishAction:(BDImagePickerFinishAction)finishAction {
    _viewController = viewController;
    _finishAction = finishAction;
    _allowsCustomEditing = allowsEditing;
  //  UIActionSheet *sheet = nil;
    
    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"请选择自定义图片" message:@"" preferredStyle:UIAlertControllerStyleActionSheet];
       //默认只有标题 没有操作的按钮:添加操作的按钮 UIAlertAction
       

       //展示
      
    
    
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        
        WEAKSELF
        LCActionSheet * actt = [LCActionSheet sheetWithTitle:@"请选择操作类型" buttonTitles:@[@"拍照",@"从相册选择"] redButtonIndex:10086 clicked:^(NSInteger buttonIndex) {
            STRONGSELFFor(weakSelf)
            NSLog(@"-------%ld",buttonIndex);
            if (buttonIndex==0) {
                dispatch_async(dispatch_get_main_queue(), ^{
                 UIImagePickerController *picker = [[UIImagePickerController alloc] init];
                   picker.delegate = self;
                   picker.sourceType = UIImagePickerControllerSourceTypeCamera;
                   picker.allowsEditing = strongSelf.allowsEditing;
                   picker.modalPresentationStyle = 0;
                   [strongSelf.viewController presentViewController:picker animated:YES completion:nil];
                   strongSelf.imagePicker = picker;
                     });
                
              
            }else if (buttonIndex==1){

                 dispatch_async(dispatch_get_main_queue(), ^{
                
                              UIImagePickerController *picker = [[UIImagePickerController alloc] init];
                                  picker.delegate = self;
                                  picker.allowsEditing = strongSelf.allowsEditing;
                                  picker.modalPresentationStyle = 0;
                                  [ strongSelf.viewController presentViewController:picker animated:YES completion:nil];
                                  strongSelf.imagePicker = picker;
                            });
                
            }
        }];
        actt.textColor = kRGBColor(51, 51, 51);
        actt.textFont = [UIFont systemFontOfSize:16];
        [actt show];

    }else {
        WEAKSELF
        LCActionSheet * actt = [LCActionSheet sheetWithTitle:@"请选择操作类型" buttonTitles:@[@"从相册选择"] redButtonIndex:10086 clicked:^(NSInteger buttonIndex) {
            STRONGSELFFor(weakSelf)
            NSLog(@"-------%ld",buttonIndex);
            if (buttonIndex==0) {
        
                
                dispatch_async(dispatch_get_main_queue(), ^{
                         
                                       UIImagePickerController *picker = [[UIImagePickerController alloc] init];
                                           picker.delegate = self;
                                           picker.allowsEditing = strongSelf.allowsEditing;
                                           picker.modalPresentationStyle = 0;
                                           [ strongSelf.viewController presentViewController:picker animated:YES completion:nil];
                                           strongSelf.imagePicker = picker;
                                     });
                
              
            }else if (buttonIndex==1){

          
                
            }
        }];
        actt.textColor = kRGBColor(51, 51, 51);
        actt.textFont = [UIFont systemFontOfSize:16];
        [actt show];
        
    }
//    dispatch_async(dispatch_get_main_queue(), ^{
//       // UI更新代码
//         UIView *window = [UIApplication sharedApplication].keyWindow;
//        // [sheet showInView:window];
//
//         [_viewController presentViewController:alertVc animated:YES completion:nil];
//
//    });
  
}


- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    NSString *title = [actionSheet buttonTitleAtIndex:buttonIndex];
    if ([title isEqualToString:@"拍照"]) {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        picker.allowsEditing = _allowsEditing;
        picker.modalPresentationStyle = 0;
        [_viewController presentViewController:picker animated:YES completion:nil];
        _imagePicker = picker;
        
    }else if ([title isEqualToString:@"从相册选择"]) {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        picker.allowsEditing = _allowsEditing;
        picker.modalPresentationStyle = 0;
        [_viewController presentViewController:picker animated:YES completion:nil];
        _imagePicker = picker;
    }else {
        bdImagePickerInstance = nil;
    }
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    UIImage *image = info[UIImagePickerControllerEditedImage];
    if (image == nil) {
        image = info[UIImagePickerControllerOriginalImage];
    }
    
    if (_allowsCustomEditing==YES) {
        
        [self cropImage:image];

    }else{
        if (_finishAction) {
            _finishAction(image);
        }
        
        [picker dismissViewControllerAnimated:YES completion:^{}];
        
        bdImagePickerInstance = nil;
    }

}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    if (_finishAction) {
        _finishAction(nil);
    }
    
    [picker dismissViewControllerAnimated:YES completion:^{}];
    
    bdImagePickerInstance = nil;
}
- (void)cropImage: (UIImage *)image {
    ClipViewController *viewController = [[ClipViewController alloc] init];
    viewController.image = image;
    viewController.picker = _imagePicker;
    viewController.controller = _viewController;
    viewController.delegate = self;
    viewController.isTakePhoto = NO;
    viewController.modalPresentationStyle = 0;
    [_imagePicker presentViewController:viewController animated:NO completion:nil];
    
}
#pragma mark -- ClipPhotoDelegate
- (void)clipPhoto:(UIImage *)image
{
    //YYLog(@"ClipPhotoDelegate");
    if (_finishAction) {
        _finishAction(image);
    }
    //    if (self.delegate && [self.delegate respondsToSelector:@selector(CameraTakePhoto:)]) {
    //        [self dismissViewControllerAnimated:YES completion:nil];
    //        [self.delegate CameraTakePhoto:image];
    //    }
    
}

//获取当前屏幕显示的viewcontroller
- (UIViewController *)getCurrentVC
{
    UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
    
    UIViewController *currentVC = [self getCurrentVCFrom:rootViewController];
    
    return currentVC;
}

- (UIViewController *)getCurrentVCFrom:(UIViewController *)rootVC
{
    UIViewController *currentVC;
    
    if ([rootVC presentedViewController]) {
        // 视图是被presented出来的
        
        rootVC = [rootVC presentedViewController];
    }
    
    if ([rootVC isKindOfClass:[UITabBarController class]]) {
        // 根视图为UITabBarController
        
        currentVC = [self getCurrentVCFrom:[(UITabBarController *)rootVC selectedViewController]];
        
    } else if ([rootVC isKindOfClass:[UINavigationController class]]){
        // 根视图为UINavigationController
        
        currentVC = [self getCurrentVCFrom:[(UINavigationController *)rootVC visibleViewController]];
        
    } else {
        // 根视图为非导航类
        
        currentVC = rootVC;
    }
    
    return currentVC;
}

@end
